# -*- coding: utf-8 -*-

"""
Description:
"""
from bs4 import BeautifulSoup


def extract_product_links(html_content):
    """提取商品搜索结果页中的链接

    Args:
        html_content (_type_): html 文本

    Returns:
        _type_: 链接列表
    """
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(html_content, "html.parser")

    # 查找所有带有search-list-title类的链接
    product_links = []
    for link in soup.find_all("a", class_="search-list-title"):
        href = link.get("href")
        if href:
            # 获取完整的URL（如果需要的话）
            full_url = (
                f"https://www.elabscience.cn{href}" if href.startswith("/") else href
            )
            product_links.append(full_url)

    return product_links


def extract_search_result(html_content):
    """
    提取商品搜索结果信息

    Args:
        html_content (str): HTML内容

    Returns:
        list: 商品信息列表
    """
    soup = BeautifulSoup(html_content, "html.parser")
    products = []

    search_list = soup.find("div", attrs={"id": "home"})
    # 查找所有商品div
    if search_list:
        product_divs = search_list.find_all("div", class_="border-b")

        for div in product_divs:
            product = {}
            # 提取商品标题
            title_elem = div.find("a", class_="search-list-title")
            if title_elem:
                product["name"] = title_elem.find("span", class_="reg_tag").text.strip()

            # 提取中文名称
            chinese_name = div.find("div", class_="reg_tag")
            if chinese_name:
                product["chinese_name"] = chinese_name.text.strip()

            # 提取商品链接
            product_link = div.find("a", class_="pc-fs-20 search-list-title")
            if product_link:
                product["link"] = "http://wbm.elabscience.cn/" + product_link.get(
                    "href"
                )

            # 提取sku
            sku_ul = div.find("ul", class_="use-select-list")
            if sku_ul:
                sku_lis = sku_ul.find_all("li")
                sku_list = []
                for li in sku_lis:
                    sku_list.append(
                        {
                            "price": li.get("data-price"),
                            "spec": li.text.replace(" ", ""),
                        }
                    )
                product["sku_list"] = sku_list

            # 提取货号
            product_ul = div.find("ul", class_="use-row pc-ml-2 mobile-m-x-0")
            product_li = product_ul.find("li")
            if product_li:
                # 在li元素中查找reg_tag类的span
                product_number = product_li.find("span", class_="reg_tag")
                if product_number:
                    product["code"] = product_number.text.strip()

            products.append(product)

        return products
    return []


def extract_product_detail(html_content):
    """提取商品详情页中的信息

    Args:
        html_content (_type_): html 文本

    Returns:
        _type_: 商品信息
    """
    soup = BeautifulSoup(html_content, "html.parser")
    info_block = soup.find("div", class_="row pc-mt-3 pt-3")
    # 提取基本信息
    product_info = {
        "en_name": info_block.find("h2", class_="js-p-title").text.strip(),
        "zh_name": info_block.find("h1", class_="fs_16")
        .text.replace("中文名称：", "")
        .strip(),
        "pro_code": info_block.find("span", class_="js-huohao").text.strip(),
        "alias": info_block.find("textarea", class_="zbjc-flex").text.strip(),
    }

    # 提取价格信息
    prices = []
    for price_span in info_block.find_all("span", class_="price_span"):
        price = price_span.find("text").text.strip()
        prices.append(price.replace("¥", ""))
    product_info["价格"] = prices

    # 提取规格信息
    sizes = []
    for size_span in info_block.find_all("span", class_="size_span"):
        sizes.append(size_span.text.strip())
    product_info["规格"] = sizes

    # 组合价格和规格生成 sku 列表
    sku_list = []
    for i in range(len(sizes)):
        sku = {"spec": sizes[i], "price": prices[i] if i < len(prices) else None}
        sku_list.append(sku)
    product_info["sku_list"] = sku_list

    # 提取产品参数
    params = {}
    for tr in info_block.find_all("tr"):
        td = tr.find_all("td")
        if len(td) == 2:
            key = td[0].text.strip()
            value = td[1].text.strip()
            if key and value:
                params[key] = value
    product_info["产品参数"] = params

    return product_info
